package com.deng.template;

import com.deng.common.templates.DirectiveHandler;
import com.deng.common.templates.TemplateDirective;
import com.deng.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.List;
@Component
public class HotsTemplate extends TemplateDirective {
    @Autowired
    RedisUtil redisUtil;
    @Override
    public String getName() {
        return "hots";
    }

    @Override
    public void execute(DirectiveHandler handler) throws Exception {
        //获取week:rank中缓存的值
        String key="week:rank";
        Set<ZSetOperations.TypedTuple> typedTuples=redisUtil.getZSetRank(key,0,6);
        List<Map> hotPosts=new ArrayList<>();
        for (ZSetOperations.TypedTuple typedTuple : typedTuples) {
            Map<String,Object> map=new HashMap<>();
            Object value=typedTuple.getValue();//文章的id
            String postKey="rank:post:"+value;
            map.put("id",value);
            map.put("title",redisUtil.hget(postKey,"post:title"));
            map.put("commentCount",typedTuple.getScore());
            hotPosts.add(map);
        }
        handler.put(RESULTS,hotPosts).render();
    }
}
